// pages/my/my.js
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
const app = getApp();

Page({
  data: {
    // 登录状态
    isLogin: false,
    
    // 当前用户信息
    currentUser: {},
    
    // 用户详细信息
    userInfo: {
      name: '',
      avatar: '',
      verified: false
    },
    
    // 送花统计
    flowerStats: {
      sent: 0,
      received: 0,
      matched: 0
    },
    
    // 今日送花状态
    todayFlowerUsed: false,
    lastFlowerTime: '',
    
    // 加载状态
    loading: false
  },

  onLoad(options) {
    console.log('我的页面加载');
  },

  async onShow() {
    console.log('我的页面显示');
    await this.checkLoginStatus();
    if (this.data.isLogin) {
      this.loadUserData();
    }
  },

  // 检查登录状态
  async checkLoginStatus() {
    const currentUser = app.globalData.currentUser;
    const isLogin = currentUser && currentUser.isLogin;
    
    this.setData({
      isLogin: isLogin,
      currentUser: currentUser
    });
    
    if (isLogin) {
      await this.checkTodayFlowerStatus();
    }
  },

  // 检查今日送花状态
  async checkTodayFlowerStatus() {
    const todayFlowerKey = `todayFlower_${util.formatDate(new Date())}`;
    const todayFlowerData = wx.getStorageSync(todayFlowerKey) || {};
    
    // 检查今日是否已送花
    const hasFlowerToday = Object.keys(todayFlowerData).length > 0;
    let lastFlowerTime = '';
    
    if (hasFlowerToday) {
      // 从API获取最后一次送花时间
      try {
        const response = await api.getLastFlowerTime();
        if (response && response.code === 0 && response.data) {
          lastFlowerTime = response.data.lastFlowerTime;
        }
      } catch (error) {
        console.error('获取送花时间失败:', error);
      }
    }
    
    this.setData({
      todayFlowerUsed: hasFlowerToday,
      lastFlowerTime: lastFlowerTime
    });
  },

  // 加载用户数据
  async loadUserData() {
    try {
      this.setData({ loading: true });
      
      // 并行加载用户信息和统计数据
      await Promise.all([
        this.loadUserProfile(),
        this.loadFlowerStats()
      ]);
      
    } catch (error) {
      console.error('加载用户数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 加载用户资料
  async loadUserProfile() {
    try {
      const { currentUser } = this.data;
      
      // 从API加载用户信息
      const response = await api.getUserProfile(currentUser.userNum);
      
      if (response && response.code === 0 && response.data && response.data.length > 0) {
        const profile = response.data[0];
        this.setData({
          userInfo: {
            name: profile.name,
            avatar: profile.avatar || util.getDefaultAvatar(profile.gender),
            verified: profile.verified === 1 // 1:验证过的会员；2:未验证的非会员
          }
        });
      }
      
    } catch (error) {
      console.error('加载用户资料失败:', error);
      throw error;
    }
  },

  // 加载送花统计
  async loadFlowerStats() {
    try {
      // 从API加载送花统计
      const response = await api.getFlowerStats(this.data.currentUser.userNum);
      
      const stats = response && response.code === 0 ? response.data : {
        sent: 0,
        received: 0,
        matched: 0
      };
      
      this.setData({ flowerStats: stats });
      
    } catch (error) {
      console.error('加载送花统计失败:', error);
      throw error;
    }
  },

  // 登录按钮点击
  async onLogin() {
    try {
      this.setData({ loading: true });
      
      // 调用微信登录
      const code = await app.login();
      
      // 获取用户手机号授权
      await new Promise((resolve, reject) => {
        wx.showModal({
          title: '登录提示',
          content: '需要获取您的手机号来完成登录',
          confirmText: '立即登录',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              resolve();
            } else {
              reject(new Error('用户取消登录'));
            }
          }
        });
      });
      
      // 更新登录状态
      app.globalData.currentUser.isLogin = true;
      
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      });
      
      // 刷新页面数据
      this.checkLoginStatus();
      this.loadUserData();
      
    } catch (error) {
      console.error('登录失败:', error);
      wx.showToast({
        title: '登录失败',
        icon: 'error'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 头像点击
  onAvatarTap() {
    wx.showActionSheet({
      itemList: ['查看头像', '更换头像'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 预览头像
          wx.previewImage({
            urls: [this.data.userInfo.avatar || '/assets/images/default-avatar.png']
          });
        } else if (res.tapIndex === 1) {
          // 更换头像
          this.changeAvatar();
        }
      }
    });
  },

  // 更换头像
  changeAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        
        wx.showToast({
          title: '头像更新成功',
          icon: 'success'
        });
        
        // 更新本地头像显示
        this.setData({
          'userInfo.avatar': tempFilePath
        });
        
        // 实际项目中这里需要上传到服务器
      },
      fail: (err) => {
        console.error('选择图片失败:', err);
      }
    });
  },

  // 编辑资料
  onEditProfile() {
    wx.navigateTo({
      url: '/pages/edit-profile/edit-profile'
    });
  },

  // 我送出的花
  onSentFlowers() {
    wx.navigateTo({
      url: '/pages/sent-flowers/sent-flowers'
    });
  },

  // 收到的花
  onReceivedFlowers() {
    wx.navigateTo({
      url: '/pages/received-flowers/received-flowers'
    });
  },

  // 匹配记录
  onMatchRecords() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },

  // 系统设置
  onSettings() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },

  // 帮助与反馈
  onHelp() {
    wx.showModal({
      title: '帮助与反馈',
      content: '如有问题或建议，请联系客服微信：yuanlaixiangyu_cs',
      confirmText: '复制微信号',
      cancelText: '知道了',
      success: (res) => {
        if (res.confirm) {
          wx.setClipboardData({
            data: 'yuanlaixiangyu_cs',
            success: () => {
              wx.showToast({
                title: '已复制到剪贴板',
                icon: 'success'
              });
            }
          });
        }
      }
    });
  },

  // 关于我们
  onAbout() {
    wx.showModal({
      title: '关于青鸟传信',
      content: '青鸟传信 v1.0.0\n\n一款专注于真实、可靠的相亲信息展示与匹配的小程序。通过每日一次的"送花"互动表达心意，双向匹配后通知管理员进行线下牵线。\n\n© 2024 青鸟传信团队',
      confirmText: '知道了',
      showCancel: false
    });
  },

  // 退出登录
  onLogout() {
    wx.showModal({
      title: '退出登录',
      content: '确定要退出登录吗？',
      confirmText: '退出',
      cancelText: '取消',
      confirmColor: '#E74C3C',
      success: (res) => {
        if (res.confirm) {
          this.performLogout();
        }
      }
    });
  },

  // 执行退出登录
  performLogout() {
    try {
      // 清除登录状态
      app.globalData.currentUser.isLogin = false;
      app.globalData.currentUser.userInfo = null;
      app.globalData.currentUser.sessionKey = null;
      
      // 清除本地存储的用户信息
      wx.removeStorageSync('userInfo');
      wx.removeStorageSync('sessionKey');
      
      // 重置页面数据
      this.setData({
        isLogin: false,
        userInfo: {
          name: '',
          avatar: '',
          verified: false
        },
        flowerStats: {
          sent: 0,
          received: 0,
          matched: 0
        },
        todayFlowerUsed: false,
        lastFlowerTime: ''
      });
      
      wx.showToast({
        title: '已退出登录',
        icon: 'success'
      });
      
    } catch (error) {
      console.error('退出登录失败:', error);
      wx.showToast({
        title: '退出失败',
        icon: 'error'
      });
    }
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '青鸟传信 - 真实可靠的相亲平台',
      path: '/pages/index/index',
      imageUrl: '/assets/images/share-image.png'
    };
  }
});